import 'dart:async';
import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:zebra/consts/datawedge_events.dart';
import 'package:zebra/models/scan_result.dart';
import 'package:zebra/models/scanner_status.dart';
export 'package:zebra/consts/scanner_status_type.dart';

class XqZebra {
  static const EventChannel _eventChannel = EventChannel('channels/scan');
  static const MethodChannel _methodChannel = MethodChannel('channels/command');
  static late StreamSubscription _stream;
  static const String _softScanTrigger =
      'com.symbol.datawedge.api.SOFT_SCAN_TRIGGER';

  static const String _scannerPlugin =
      'com.symbol.datawedge.api.SCANNER_INPUT_PLUGIN';

  static Future<String> platformVersion() async {
    final String version =
        await _methodChannel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<void> _sendDataWedgeCommand(
      String command, String parameter) async {
    try {
      String argumentAsJson =
          jsonEncode({"command": command, "parameter": parameter});

      await _methodChannel.invokeMethod(
          'sendDataWedgeCommandStringParameter', argumentAsJson);
    } on PlatformException {
      //  Error invoking Android method
    }
  }

  static Future<void> _createProfile(String profileName) async {
    try {
      await _methodChannel.invokeMethod('createDataWedgeProfile', profileName);
    } on PlatformException {}
  }

  static Future<void> _listenScannerStatus() async {
    try {
      await _methodChannel.invokeMethod('listenScannerStatus');
    } on PlatformException {}
  }

  static startScan() {
    _sendDataWedgeCommand(_softScanTrigger, 'START_SCANNING');
  }

  static stopScan() {
    _sendDataWedgeCommand(_softScanTrigger, 'STOP_SCANNING');
  }

  static void enableScanner(bool enable) {
    String command = enable ? 'ENABLE_PLUGIN' : 'DISABLE_PLUGIN';
    _sendDataWedgeCommand(_scannerPlugin, command);
  }

  static void activateScanner(bool activate) {
    String command = activate ? 'RESUME_PLUGIN' : 'SUSPEND_PLUGIN';
    _sendDataWedgeCommand(_scannerPlugin, command);
  }

  static listen(void Function(String) callback,
      {String profileName = 'XqZebra',
      void Function(ScannerStatus result)? onStatusUpdate,
      void Function(dynamic)? onError}) {
    _createProfile(profileName);

    _stream = _eventChannel.receiveBroadcastStream().listen((dynamic event) {
      Map eventObj = jsonDecode(event as String);
      String type = eventObj['EVENT_NAME'];
      switch (type) {
        case SCAN_RESULT:
          callback(ScanResult.fromEvent(event).data);
          break;
        case SCANNER_STATUS:
          if (onStatusUpdate != null)
            onStatusUpdate(ScannerStatus.fromEvent(event));
          break;
        default:
      }
    }, onError: onError);

    _listenScannerStatus();
  }

  static remove() {
    if (_stream != null) {
      _stream.cancel();
    }
  }
}
